<?php

namespace addons\shopro\controller;

use app\admin\model\shopro\tokens\Config;
use app\admin\model\shopro\Withdraw as WithdrawModel;
use addons\shopro\service\Withdraw as WithdrawLibrary;

class Withdraw extends Common
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function index() 
    {
        $user = auth_user();
        $currency_type=request()->get('currency_type');
        if(!is_numeric($currency_type)){
            $this->error('参数错误');
        }
        $withdraws = WithdrawModel::where(['user_id' => $user->id,'currency_type'=>intval($currency_type)])->order('id desc')->paginate($this->request->param('list_rows', 10))->each(function ($withdraw) {
            $withdraw->hidden(['withdraw_info']);
        });

        $this->success('获取成功', $withdraws);
    }


    // 兑换规则
    public function rules()
    {
        $user = auth_user();
        $config = (new WithdrawLibrary($user))->config;
        $config['tokens']=Config::get(1)->field('current_price')->find();
        $this->success('兑换规则', $config);
    }


    // 发起兑换请求
    public function apply()
    {


        $currentHour = date('H');
        if($currentHour<9 || $currentHour>=17){
            error_stop('每天兑换开放时间是9:00-17:00，周六周日除外');
        }

        if(sheep_config('shop.basic.withdrawal')=='0')
        {
            error_stop('操作不在时间范围内');
        }


        $user = auth_user();

        $params = $this->request->param();

        $this->svalidate($params, ".apply");

        switch ($params['currency_type']){
            case 1:
                if(!$user['moy_switch']){
                    $this->error('系统接口维护中。。');
                }
                break;
            case 2:
                if(!$user['wit_switch']){
                    $this->error('系统接口维护中。。');
                }
                break;
            case 3:
                if(!$user['bean_switch']){
                    $this->error('系统接口维护中。。');
                }
                break;
            default:
                $this->error('参数错误');

        }

        if ($user->lock_status == 1 && ($params['currency_type'] == 2 || $params['currency_type'] == 3)) {
            $this->error('账号异常。');
        }


        if($params['money']%100!=0){
            $this->error('兑换必须是100的倍数');
        }

        if ($user->rep_password != md5(md5($params['rep_password']) . $user->salt)) {
            error_stop('支付密码错误！');
        }



        $withdrawLib = new WithdrawLibrary($user);
        $withdraw = $withdrawLib->apply($params);

        $this->success('申请成功', $withdraw);
    }
}
